#Alex Gazmararian
#afg2@princeton.edu
#January 18, 2024

#Purpose: This script estimates funds that could be raised by the proposed model,
# under different assumptions about donation allocations

#Load packages
library(tidyverse)
library(kableExtra)
library(here)

#Load survey data
g <- readRDS(here("data", "CCES", "ces_processed.rds"))

#Load net metering data
fund <- readRDS(here("data", "netmetering", "netmeterrev.rds"))

#Merge net metering data with survey data by states
fund$inputstate <- state.name[match(fund$state,state.abb)]
d <- left_join(g, fund, by = "inputstate")

#Check missing states
anti_join(g,fund,by="inputstate") %>% select(inputstate) %>% unique() #missing Oregon,Alabama, and DC, and Delaware

#Table 3: estimated revenue-raising potential under allocation scenarios and implications for scale development
solar.tab <- d %>%
  filter(!is.na(rev) & solarinterest == 1) %>%
  group_by(inputstate,rev) %>%
  summarize(
    self_donate = mean(self_donate)/20,
    others_donate = mean(others_donate)/20
  ) %>% #create average donation by state for self, other
  ungroup() %>%
  summarize(
    self = sum(rev * self_donate),
    other = sum(rev * others_donate),
    med = sum((rev * self_donate * .5) + (rev * others_donate * .5)),
    lbextreme = sum(rev * others_donate * .5)
  ) %>%
  pivot_longer(c(self:lbextreme)) %>%
  mutate(
    res_watt = (value / 2.95) / 1000, #kW of power for residential solar
    res_home = res_watt / 6, #number of homes with 6kW
    com_watt = (value / 0.99) / 1000, #kW of power for commercial ground mount solar
    com_farm = com_watt / 1000, #number of 1mW farms
    value = paste0("\\",scales::dollar(value))
  )
solar.tab$name <- c("Own donations", "Neighbor donations",
                    "Own (50\\%) $+$ neighbor (50\\%) donations",
                    "Neighbor donations (discounted 50\\%)")
#reorder
solar.tab <- solar.tab[c(1,3,2,4),]
names(solar.tab) <- c("Allocation Measure", "Revenue", "kW", "Homes", "kW", "Farms")
kableExtra::kbl(solar.tab, booktabs = TRUE, digits = 0, escape = FALSE, format = "latex") %>%
  kableExtra::add_header_above(c(" "=2, "Residential"=2, "Utility"=2)) %>%
  cat(., file = here("output", "tables", "solarest.txt"))